#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QFileDialog>
#include "employee.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    currentIndex = -1;

    // 设置表格列数和标题
    ui->employeesTable->setRowCount(10);
    ui->employeesTable->setColumnCount(6);
    QStringList headers;
    headers << "ID" << "姓名" << "年龄" << "部门" << "职位" << "薪资";
    ui->employeesTable->setHorizontalHeaderLabels(headers);

    // 设置表格选择行为
    ui->employeesTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->employeesTable->setSelectionMode(QAbstractItemView::SingleSelection);

    // 为每个button 设置名字
    ui->addButton->setText("增加");
    ui->deleteButton->setText("删除");
    ui->loadButton->setText("加载");
    ui->saveButton->setText("保存");
    ui->searchButton->setText("搜索");
    ui->updateButton->setText("修改");

    ui->nameEdit->setPlaceholderText("姓名");
    ui->departmentEdit->setPlaceholderText("部门");
    ui->positionEdit->setPlaceholderText("职位");
    ui->nameLabel->setText("姓名");
    ui->departmentLabel->setText("部门");
    ui->positionLabel->setText("职位");
    ui->ageLabel->setText("年龄");
    ui->salaryLabel->setText("薪水");

    // 连接信号槽
    connect(ui->employeesTable, &QTableWidget::clicked, this, &MainWindow::on_employeesTable_clicked);
    connect(ui->addButton, &QPushButton::clicked, this, &MainWindow::on_addButton_clicked);
    connect(ui->deleteButton, &QPushButton::clicked, this, &MainWindow::on_deleteButton_clicked);
    connect(ui->loadButton, &QPushButton::clicked, this, &MainWindow::on_loadButton_clicked);
    connect(ui->saveButton, &QPushButton::clicked, this, &MainWindow::on_saveButton_clicked);
    connect(ui->searchButton, &QPushButton::clicked, this, &MainWindow::on_searchButton_clicked);
    connect(ui->updateButton, &QPushButton::clicked, this, &MainWindow::on_updateButton_clicked);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_addButton_clicked()
{
    //qDebug() << "on_addButton_clicked";
    QString name = ui->nameEdit->text();
    int age = ui->ageSpin->value();
    QString department = ui->departmentEdit->text();
    QString position = ui->positionEdit->text();
    double salary = ui->salarySpin->value();

    if (name.isEmpty()) {
        QMessageBox::warning(this, "警告", "姓名不能为空!");
        return;
    }

    Employee employee(name, age, department, position, salary);
    employees.append(employee);

    updateTable();
    clearForm();
}

void MainWindow::on_deleteButton_clicked()
{
    if (currentIndex < 0 || currentIndex >= employees.size()) {
        QMessageBox::warning(this, "警告", "请选择要删除的员工!");
        return;
    }

    employees.removeAt(currentIndex);
    currentIndex = -1;
    updateTable();
    clearForm();
}

void MainWindow::on_updateButton_clicked()
{

    if (currentIndex < 0 || currentIndex >= employees.size()) {
        QMessageBox::warning(this, "警告", "请选择要修改的员工!");
        return;
    }

    QString name = ui->nameEdit->text();
    int age = ui->ageSpin->value();
    QString department = ui->departmentEdit->text();
    QString position = ui->positionEdit->text();
    double salary = ui->salarySpin->value();

    if (name.isEmpty()) {
        QMessageBox::warning(this, "警告", "姓名不能为空!");
        return;
    }

    Employee &employee = employees[currentIndex];
    employee.setName(name);
    employee.setAge(age);
    employee.setDepartment(department);
    employee.setPosition(position);
    employee.setSalary(salary);

    updateTable();
    clearForm();
}

void MainWindow::on_searchButton_clicked()
{
    QString keyword = ui->searchEdit->text().trimmed();

    if (keyword.isEmpty()) {
        updateTable();
        return;
    }

    ui->employeesTable->setRowCount(0);

    for (int i = 0; i < employees.size(); ++i) {
        const Employee &employee = employees[i];
        if (employee.getName().contains(keyword) ||
            employee.getDepartment().contains(keyword) ||
            employee.getPosition().contains(keyword)) {

            int row = ui->employeesTable->rowCount();
            ui->employeesTable->insertRow(row);

            ui->employeesTable->setItem(row, 0, new QTableWidgetItem(QString::number(employee.getId())));
            ui->employeesTable->setItem(row, 1, new QTableWidgetItem(employee.getName()));
            ui->employeesTable->setItem(row, 2, new QTableWidgetItem(QString::number(employee.getAge())));
            ui->employeesTable->setItem(row, 3, new QTableWidgetItem(employee.getDepartment()));
            ui->employeesTable->setItem(row, 4, new QTableWidgetItem(employee.getPosition()));
            ui->employeesTable->setItem(row, 5, new QTableWidgetItem(QString::number(employee.getSalary())));
        }
    }
}


void MainWindow::on_saveButton_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, "保存员工数据", "", "文本文件 (*.txt)");
    if (fileName.isEmpty()) return;

    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "错误", "无法打开文件进行写入!");
        return;
    }

    QTextStream out(&file);
    for (const Employee &employee : employees) {
        out << employee.getId() << ","
            << employee.getName() << ","
            << employee.getAge() << ","
            << employee.getDepartment() << ","
            << employee.getPosition() << ","
            << employee.getSalary() << "\n";
    }

    file.close();
    QMessageBox::information(this, "成功", "员工数据已保存!");
}


void MainWindow::on_loadButton_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, "加载员工数据", "", "文本文件 (*.txt)");
    if (fileName.isEmpty()) return;

    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "错误", "无法打开文件进行读取!");
        return;
    }

    employees.clear();
    QTextStream in(&file);
    while (!in.atEnd()) {
        QString line = in.readLine();
        QStringList fields = line.split(",");

        if (fields.size() == 6) {
            int id = fields[0].toInt();
            QString name = fields[1];
            int age = fields[2].toInt();
            QString department = fields[3];
            QString position = fields[4];
            double salary = fields[5].toDouble();

            Employee employee(name, age, department, position, salary);
            employees.append(employee);

            // 更新nextId以确保新添加的员工ID不会重复
            if (id >= Employee::getNextId()) {
                Employee::setNextId(id + 1);
            }
        }
    }

    file.close();
    updateTable();
    QMessageBox::information(this, "成功", "员工数据已加载!");
}


void MainWindow::on_employeesTable_clicked(const QModelIndex &index)
{
    currentIndex = index.row();
    loadEmployeeToForm(currentIndex);
}

void MainWindow::updateTable()
{
    ui->employeesTable->setRowCount(0);

    for (int i = 0; i < employees.size(); ++i) {
        const Employee &employee = employees[i];

        int row = ui->employeesTable->rowCount();
        ui->employeesTable->insertRow(row);

        ui->employeesTable->setItem(row, 0, new QTableWidgetItem(QString::number(employee.getId())));
        ui->employeesTable->setItem(row, 1, new QTableWidgetItem(employee.getName()));
        ui->employeesTable->setItem(row, 2, new QTableWidgetItem(QString::number(employee.getAge())));
        ui->employeesTable->setItem(row, 3, new QTableWidgetItem(employee.getDepartment()));
        ui->employeesTable->setItem(row, 4, new QTableWidgetItem(employee.getPosition()));
        ui->employeesTable->setItem(row, 5, new QTableWidgetItem(QString::number(employee.getSalary())));
    }
}


void MainWindow::clearForm()
{
    ui->nameEdit->clear();
    ui->ageSpin->setValue(0);
    ui->departmentEdit->clear();
    ui->positionEdit->clear();
    ui->salarySpin->setValue(0.0);
    currentIndex = -1;
}


void MainWindow::loadEmployeeToForm(int index)
{
    if (index < 0 || index >= employees.size()) return;

    const Employee &employee = employees[index];
    ui->nameEdit->setText(employee.getName());
    ui->ageSpin->setValue(employee.getAge());
    ui->departmentEdit->setText(employee.getDepartment());
    ui->positionEdit->setText(employee.getPosition());
    ui->salarySpin->setValue(employee.getSalary());
}

